﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace UFrame
{
    public class WebGMControlServerEditor : EditorWindow
    {
        [MenuItem("Plateface/GM/GMWeb")]
        public static void OpenGM()
        {
            var w = GetWindow<WebGMControlServerEditor>("发送GM命令");
            w.Show();
            var web = FindObjectOfType<WebGMControl>();
            if (web != null)
            {
                w.curIP = web.curIP;
            }
        }

        public string curIP = "127.0.0.1";
        public string curPort = "9099";
        public string serviceIP = "127.0.0.1";
        public string servicePort = "9098";
        public int msgID = 0;
        public string sendStr = String.Empty;

        public TcpClient tcpClient;
        private BufferVerify bufferVerify = new BufferVerify();
        private Encoding encoding = Encoding.UTF8;
        private bool isMonitor = true;
        private static BufferVerify.BufferInfo curBufferInfo = new BufferVerify.BufferInfo();
        private NetworkStream tcpStream;
        private bool isReceive = true;

        public void OnFocus()
        {
            Connect();
        }

        public void OnEnable()
        {
            EventMa.Unregister<WebGMJson>(WebGMEditorArgs.EventId,OnWeb);
            EventMa.Register<WebGMJson>(WebGMEditorArgs.EventId, OnWeb);
        }

        public void OnWeb(WebGMJson json)
        {
            if (json.msgId == 1000)
            {
                WebGMControl.sb.AppendLine("编辑器: " + json.content);
            }
        }
        
        public async void ReceiveInfo()
        {
            if (tcpStream != null)
            {
                while (isReceive)
                {
                    byte[] b = new byte[2500];
                    var count = await tcpStream.ReadAsync(b, 0, b.Length);
                    byte[] packAry = new byte[count];
                    Array.Copy(b, 0, packAry, 0, count);
                    curBufferInfo = bufferVerify.ReceiveStream(packAry, curBufferInfo);
                    if (curBufferInfo.isFull)
                    {
                        //发送事件
                        string data = encoding.GetString(curBufferInfo.contentAry, 0, curBufferInfo.contentAry.Length);
                        var obj = JsonUtility.FromJson<WebGMJson>(data);
                        if (obj == null)
                        {
                            //Debug.Log("序列化不成功\n" + data);
                        }

                        EventMa.Notify<WebGMJson>(WebGMEditorArgs.EventId, obj);
                        //Debug.Log("服务器监听UPD " + data);
                        OnReceiveGM(obj);

                        //开始释放
                        curBufferInfo.Clear();
                    }
                }
            }
        }

        public async void Connect()
        {
            if (Application.isEditor && string.IsNullOrEmpty(curIP))
            {
                curIP = "127.0.0.1";
            }

            if (tcpClient != null && tcpClient.Connected)
            {
                return;
            }


            tcpClient = new TcpClient();
            if (string.IsNullOrEmpty(serviceIP))
                serviceIP = "127.0.0.1";
            if (string.IsNullOrEmpty(servicePort))
                servicePort = "9098";

            try
            {
                await tcpClient.ConnectAsync(serviceIP, Convert.ToInt32(servicePort));
                WebGMControl.sb.AppendLine("连接成功服务器");
                tcpStream = tcpClient.GetStream();
                ReceiveInfo();
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message + "   " + serviceIP + "  " + servicePort);
            }


           
        }

        public void OnGUI()
        {
            if (tcpClient != null)
                EditorGUILayout.LabelField("连接状态" + tcpClient.Connected);
            curIP = EditorGUILayout.TextField("连接地址: ", curIP);
            curPort = EditorGUILayout.TextField("端口: ", curPort);
            msgID = EditorGUILayout.IntField("消息ID", msgID);
            sendStr = EditorGUILayout.TextArea(sendStr, GUILayout.Height(80));

            if (GUILayout.Button("发送给客户端", GUILayout.Height(30)))
            {
                if (tcpClient.Connected == false)
                {
                    WebGMControl.sb.AppendLine("没有连接客户端,无法发送消息");
                    return;
                }

                var net = tcpClient.GetStream();
                WebGMJson obj = new WebGMJson();
                obj.msgId = msgID;
                obj.content = sendStr;
                obj.ip = curIP;
                obj.port = curPort;
                string jsonStr = JsonUtility.ToJson(obj);
                var data = bufferVerify.SendRPC(1, jsonStr, encoding);
                net.Write(data, 0, data.Length);
                WebGMControl.sb.AppendLine("发送给客户端信息" + data.Length);
            }
        }


        public void OnReceiveGM(WebGMJson data)
        {
            // WebGMControl.sb.AppendLine(data.msgId.ToString());
            // WebGMControl.sb.AppendLine(data.ip);
            // WebGMControl.sb.AppendLine(data.port);
            // WebGMControl.sb.AppendLine(data.content);
        }
    }
}